package com.kamistoat.meimeimall.meimeimallpayment.dubbo;

import com.kamistoat.meimeimall.common.To.paymentTo.PayAsyncTo;
import com.kamistoat.meimeimall.common.dubboInterface.PaymentDubboInterface;
import com.kamistoat.meimeimall.meimeimallpayment.dao.PaymentRecordDao;
import com.kamistoat.meimeimall.meimeimallpayment.entity.PaymentRecordEntity;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class PaymentDubboInterfaceImpl implements PaymentDubboInterface {
    protected Logger logger = LoggerFactory.getLogger(PaymentDubboInterfaceImpl.class);

    @Autowired
    PaymentRecordDao paymentRecordDao;

    /**
     * 收到支付成功回调后，保存支付流水
     *
     * @param businessActionContext
     * @param payAsyncTo
     */
    @Override
    @Transactional
    public void savePaymentInfo(BusinessActionContext businessActionContext, PayAsyncTo payAsyncTo) {
        PaymentRecordEntity paymentRecordEntity = new PaymentRecordEntity();
        paymentRecordEntity.setThirdPaymentTradeSn(payAsyncTo.getTrade_no());
        paymentRecordEntity.setOrderSn(payAsyncTo.getOut_trade_no());
        paymentRecordEntity.setThirdPaymentTradeStatus(payAsyncTo.getTrade_status());
        paymentRecordEntity.setThirdPaymentTradeCallbackTime(payAsyncTo.getNotify_time());
        paymentRecordEntity.setTotalAmount(new BigDecimal(payAsyncTo.getTotal_amount()));
        paymentRecordEntity.setPaymentContent(payAsyncTo.getSubject());
        paymentRecordDao.insert(paymentRecordEntity);
    }

    /**
     * 收到支付成功回调后，保存支付流水 提交动作。
     * 但实际上不会做任何操作。
     */
    @Override
    @Transactional
    public boolean savePaymentInfoCommit(BusinessActionContext businessActionContext) {
        return true;
    }

    /**
     * 收到支付成功回调后，保存支付流水 回滚动作。
     * 同样两种情况。自身一阶段失败和其他事务分支失败
     */
    @Override
    @Transactional
    public boolean savePaymentInfoRollback(BusinessActionContext businessActionContext) {
        PayAsyncTo payAsyncTo = (PayAsyncTo) businessActionContext.getActionContext("payAsyncTo");
        try {
            paymentRecordDao.logicDeleteByOrderSn(payAsyncTo.getOut_trade_no());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
